module vlib.Util.Event;

import vlib.Types ;

struct vEvents(This, uint step){
	alias void function(This*, void*) CallBack ;
	static struct DgType {
		void function(This*, void*) cb ;
		void*	ctx ;
	}
	static assert(step > 0 );
	DgType[]	callbacks ;
	int 	p ;
	
	void fire(This* _this) {
		for( int i = 0 ; i < p ; i++ ){
			if(callbacks[i].cb !is null ) {
				callbacks[i].cb(_this, callbacks[i].ctx) ;
				callbacks[i].cb	= null ;
				callbacks[i].ctx	= null ;
			}
		}
		p	= 0 ;
	}
	
	bool un(CallBack cb, void* ctx ) {
		bool	ret  ;
		for( int i = 0 ; i < p ; i++ ){
			if( callbacks[i].cb is cb && callbacks[i].ctx is ctx ) {
				callbacks[i].cb	= null ;
				callbacks[i].ctx	= null ;
				ret	= true ;
			}
		}
		return ret ;
	}
	
	DgType* on(CallBack cb, void* ctx = null ) {
		assert(cb !is null);
		if( p is callbacks.length ){
			callbacks.length	= callbacks.length + step ;
		}
		int	i	= p;
		p++;
		callbacks[i].cb	= cb ;
		callbacks[i].ctx	= ctx ;
		return &callbacks[i] ;
	}
}